package com.zlsy.secondtime.threadcoreknowledge.stopthreads;


import java.util.LinkedList;

/**
 * @author zhouliang
 * @date 2021/1/25 19:31
 */
public class WaitTest {
    public static void main(String[] args) {
        LinkedList<String> list=new LinkedList<>();
        Data data =new Data(list);
        Producer producer = new Producer(data);
        Consumer consumer = new Consumer(data);

        Thread t1 = new Thread(producer);
        t1.setName("producer");
        Thread t2 = new Thread(consumer);
        t2.setName("consumer");
        t1.start();
        t2.start();
    }


    private static class Producer implements Runnable {
        private Data data;

        public Producer(Data data) {
            this.data = data;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                data.put();
            }
        }
    }

    private static class Consumer implements Runnable {
        private Data data;

        public Consumer(Data data) {
            this.data = data;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                data.take();
            }
        }
    }

    private static class Data {
        private int max;
        private LinkedList<String> list;

        public  Data(LinkedList<String> list) {
            this.max = 10;
            this.list = list;
        }

        public synchronized void put() {
            while (list.size() >= max) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add("1");
            System.out.println(Thread.currentThread().getName()+"仓库里面已经有了" + list.size() + "个产品。");
            this.notify();
        }

        public synchronized void take() {
            while (list.size() == 0) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"拿到了" + list.poll() + "，现在仓库还剩下：" + list.size());
            this.notify();
        }
    }
}
